﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using BLL;
using DTO;
using DevExpress.XtraTreeList.Nodes;
using DevExpress.XtraTreeList;


namespace CRM.GUI.QLHeThong
{
    public partial class frmManageUser : DevExpress.XtraEditors.XtraForm
    {
        Administrators ad = new Administrators();
        BLsupervisor sup = new BLsupervisor();
        private static int _UserId;
        private UserEntity _UserInfo;

        public frmManageUser()
        {
            InitializeComponent();
            IntialLoad();
        }

        private void IntialLoad()
        {
            cDataInTransfer data = new cDataInTransfer();
            cmbRegion.DataSource = SharedData.RegionList.Where(a => a.RegionLevel == 1).ToList();
            cmbRegion.DisplayMember = "RegionName";
            cmbRegion.ValueMember = "Region_Code";
            cmbRole.DataSource = data.LoadRole();
            cmbRole.DisplayMember = "Role_Name";
            cmbRole.ValueMember = "ID";
            // Load danh sach nguoi dung
            grdMainUser.DataSource = ad.GetAllUser();
            // Load danh sach quyen
            LoadPermitList(grdPermission, ad.LoadListPermission());
            // Load combobox vung mien
            ckbRegionCode.DisplayMember = "RegionName";
            ckbRegionCode.ValueMember = "Region_Code";
            cbxRole.DisplayMember = "Role_Name";
            cbxRole.ValueMember = "ID";
            DefaultUserIntialLoad();
        }

        private void btnAddUser_Click(object sender, EventArgs e)
        {
            if (MakeUser())
            {
                if (_User != null)
                {
                    ad.InsertUser(_User);
                    MessageBox.Show("Thêm người dùng mới thành công!");
                }
                // Trả về mặc định ban đầu
                txtLastNameUser.Text = "";
                txtFirstNameUser.Text = "";
                txtAccount.Text = "";
                txtPassword.Text = "";
                txtExtensionPhone.Text = "";
                ckbRegionCode.DataSource = null;
                cbxRole.DataSource = null;
                // refresh
                grdMainUser.DataSource = ad.GetAllUser();
            }
        }
        private UserEntity _User;
        private bool MakeUser()
        {
            UserEntity user = new UserEntity();
            if (string.IsNullOrWhiteSpace(txtLastNameUser.Text))            
            {                
                MessageBox.Show("Xin nhập họ người dùng");
                _User = null;
                txtLastNameUser.Focus();
                return false;
            }
            if (string.IsNullOrWhiteSpace(txtFirstNameUser.Text))
            {
                MessageBox.Show("Xin nhập tên người dùng");
                _User = null;
                txtFirstNameUser.Focus();
                return false;
            }
            if (string.IsNullOrWhiteSpace(ckbRegionCode.Text) || ckbRegionCode.SelectedValue == null)
            {
                MessageBox.Show("Xin nhập tên vùng miền");
                _User = null;
                ckbRegionCode.Focus();
                return false;
            }
            if (string.IsNullOrWhiteSpace(txtAccount.Text))
            {
                MessageBox.Show("Xin nhập tên tài khoản");
                _User = null;
                txtAccount.Focus();
                return false;
            }
            if (string.IsNullOrWhiteSpace(txtPassword.Text))
            {
                MessageBox.Show("Xin nhập mật khẩu");
                _User = null;
                txtPassword.Focus();
                return false;
            }
            if (string.IsNullOrWhiteSpace(txtExtensionPhone.Text))
            {
                MessageBox.Show("Xin nhập số điện thoại");
                _User = null;
                txtExtensionPhone.Focus();
                return false;
            }
            if (cbxRole.SelectedValue == null)
            {
                MessageBox.Show("Xin chọn tên vai trò");
                _User = null;
                cbxRole.Focus();
                return false;
            }
            
            user.LastName = txtLastNameUser.Text;
            user.FirstName = txtFirstNameUser.Text;
            user.Account = txtAccount.Text;
            user.Password = txtPassword.Text;
            user.TelephoneNumber = txtExtensionPhone.Text;
            user.Region_Code = (int)ckbRegionCode.SelectedValue;
            user.Role = (int)cbxRole.SelectedValue;
            _User = user;
            return true;
        }


        private void grdViewMainUser_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            Administrators admin = new Administrators();            
            var data = (UserEntity)grdViewMainUser.GetRow(grdViewMainUser.FocusedRowHandle);
            _UserId = data.UserID;
            _UserInfo = data;
            LoadPermitList(grdPermission, admin.LoadListPerEachUser(_UserId));
        }

        private void LoadPermitList(TreeList treelist, List<PermissionEntity> list)
        {         
            List<PermissionEntity> data = list;            
            treelist.DataSource = list;            
            treelist.KeyFieldName = "Permission_ID";
            treelist.ParentFieldName = "PermissionGroup_ID";
            treelist.ExpandAll();
        }

        private void grdPermission_CellValueChanging(object sender, CellValueChangedEventArgs e)
        {
            // lay id cua cot Status
            int columnID3 = grdPermission.Columns["Status"].AbsoluteIndex;
            // lay du lieu cua cot dang tuong tac
            PermissionEntity data = (PermissionEntity)grdPermission.GetDataRecordByNode(e.Node);
            // Dat lai gia tri cho root
            e.Node.SetValue(columnID3, e.Value);
            // Dat gia tri cho child cua root tuong ung
            if (data.PermissionGroup_ID == 0)
            {
                foreach (TreeListNode node in e.Node.Nodes)
                {
                    node.SetValue(columnID3, e.Value);
                    // thuc thi update phan quyen cho cac child
                    ad.UpdateUserPermit((PermissionEntity)grdPermission.GetDataRecordByNode(grdPermission.GetNodeByVisibleIndex(node.Id)), _UserId);
                }
            }
            if (data.PermissionGroup_ID == 1)
            {
                int i = 0;
                // Kiem tra tong so con duoc check 
                foreach (TreeListNode node in e.Node.ParentNode.Nodes)
                {
                    if ((bool)node.GetValue(columnID3) == true)
                    {
                        i++;
                    }
                }
                // Check cha theo con
                if (i == 1)
                {
                    if ((bool)e.Node.ParentNode.GetValue(columnID3) == true)
                    {
                        e.Node.SetValue(columnID3, e.Value);
                        ad.UpdateUserPermit((PermissionEntity)grdPermission.GetDataRecordByNode(grdPermission.GetNodeByVisibleIndex(e.Node.Id)), _UserId);
                    }
                    else
                    {
                        // Check cha khi co 1 con check
                        e.Node.ParentNode.SetValue(columnID3, e.Value);
                        ad.UpdateUserPermit((PermissionEntity)grdPermission.GetDataRecordByNode(grdPermission.GetNodeByVisibleIndex(e.Node.ParentNode.Id)), _UserId);
                    }
                }
                else
                {
                    if (i == 0)
                    {
                        e.Node.ParentNode.SetValue(columnID3, e.Value);
                        ad.UpdateUserPermit((PermissionEntity)grdPermission.GetDataRecordByNode(grdPermission.GetNodeByVisibleIndex(e.Node.ParentNode.Id)), _UserId);
                    }
                    else
                    {
                        e.Node.SetValue(columnID3, e.Value);
                        ad.UpdateUserPermit((PermissionEntity)grdPermission.GetDataRecordByNode(grdPermission.GetNodeByVisibleIndex(e.Node.Id)), _UserId);
                    }
                }
            }          
            // thuc thi phan quyen cho root
            ad.UpdateUserPermit(((PermissionEntity)grdPermission.GetDataRecordByNode(e.Node)), _UserId);
        }

        private void DefaultUserIntialLoad()
        {
            grdViewMainUser.FocusedRowHandle = 0;
            Administrators admin = new Administrators();
            var data = (UserEntity)grdViewMainUser.GetRow(grdViewMainUser.FocusedRowHandle);
            _UserId = data.UserID;
            LoadPermitList(grdPermission, admin.LoadListPerEachUser(_UserId));
        }

        private void ckbRegionCode_Click(object sender, EventArgs e)
        {
            ckbRegionCode.DataSource = SharedData.RegionList.Where(a => a.RegionLevel == 1).ToList();            
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            frmUpdateUser frm = new frmUpdateUser(_UserInfo);
            frm.ShowDialog();
            grdMainUser.DataSource = ad.GetAllUser();
        }

        private void grdViewMainUser_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            var data = (UserEntity)grdViewMainUser.GetRow(e.FocusedRowHandle);
            _UserInfo = data;
        }

        private void grdViewMainUser_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            var data = (UserEntity)grdViewMainUser.GetRow(e.RowHandle);
            Authentication au = new Authentication();
            au.UpdateUserInfo(data);
        }

        private void cbxRole_Click(object sender, EventArgs e)
        {
            cDataInTransfer data = new cDataInTransfer();
            cbxRole.DataSource = data.LoadRole();
        }

    }
}